<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8">
    <title>Video Index</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="/node_modules/layui/dist/css/layui.css" rel="stylesheet">
</head>
<body>
<!--
本「综合演示」包含：自定义头部工具栏、获取表格数据、表格重载、自定义模板、单双行显示、单元格编辑、自定义底部分页栏、表格相关事件与操作、与其他组件的结合等相对常用的功能，以便快速掌握 table 组件的使用。
-->
<div style="padding: 16px;">

    <table class="layui-hide" id="Video" lay-filter="Video"></table>

</div>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">

        <form class="layui-form layui-row layui-col-space16" onsubmit="return false;">
            <div class="layui-col-md2">
                <div class="layui-input-wrap">
                    <div class="layui-input-prefix">
                        <i class="layui-icon layui-icon-username"></i>
                    </div>
                    <input type="text" name="name" value="" placeholder="请输入源作者名称" class="layui-input"
                           lay-affix="clear">
                </div>
            </div>
            <div class="layui-col-md2">
                <select id="platformSelect" name="platformName" lay-search=""
                        style="max-height: 100px;overflow-y: auto;">
                    <option value="">加载中...</option>
                </select>
            </div>
            <div class="layui-col-md2">
                <select id="downLoadingSelect" name="status" lay-search="" style="max-height: 100px;overflow-y: auto;">

                    <!--                    <option value="1">已下载</option>-->
                    <!--                    <option value="0">未下载</option>-->
                </select>
            </div>
            <div class="layui-btn-container">
                <button id="search" class="layui-btn" lay-submit lay-filter="nameSearch">查找</button>
                <button id="delete" class="layui-btn layui-bg-red" lay-event="delete">批量删除</button>
                <button id="unEdit" class="layui-btn" lay-event="unEdit">修改为待上传</button>
                <button id="reloadErrResource" class="layui-btn" lay-event="reloadErrResource"
                        >批量重新下载
                </button>

            </div>
        </form>

    </div>

</script>


<script type="text/html" id="barDemo">
    <div class="layui-clear-space">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑文案</a>
        <a class="layui-btn layui-btn-xs" lay-event="report">错误报告</a>
        <!--        <a class="layui-btn layui-btn-xs" lay-event="more">-->
        <!--            更多-->
        <!--            <i class="layui-icon layui-icon-down"></i>-->
        <!--        </a>-->
    </div>
</script>
<script src="/node_modules/layui/dist/layui.js"></script>
<script th:inline="none">
    const videoStatus = Object.freeze({
        /**
         * 视频未下载，或下载失败
         */
        UNDOWNLOADING: {value: 0, name: '未下载'},
        /**
         * 视频已下载，但未进行抽帧等视频操作
         */
        DOWNLOADING: {value: 1, name: '已下载'},
        /**
         * 视频进行抽帧等操作完成
         */
        PROCESSED: {value: 2, name: '处理完成'},
        /**
         * 视频等待设备下载上传
         * 可上传
         */
        UPLOADABLE: {value: 3, name: '待上传'},
        /**
         * 设备下载完成
         */
        DEVICEDOWN: {value: 4, name: '设备下载完成'},
        /**
         * 设备下载完成
         */
        DEVICEUPLOAD: {value: 5, name: '上传完成'}
    });
    layui.use(['jquery', 'table', 'dropdown', 'form'], function () {
        var $ = layui.jquery;
        var table = layui.table;
        var dropdown = layui.dropdown;
        var form = layui.form;
        var layer = layui.layer;

        var selectStatus = 0;
        /* **************** */
        /*      搜索提交     */
        /* **************** */
        form.on('submit(nameSearch)', function (data) {
            var index = layer.load(0, {shade: false});
            var field = data.field; // 获得表单字段
            // var options = table.cache['Video'].config;
            //
            // options.cols[0].forEach(function(col) {
            //     if (col.field === 'medias') {
            //         col.title = '新的用户名';
            //     }
            // });
            selectStatus = parseInt(field.status);
            // 执行搜索重载
            table.reloadData('Video', {
                url: '/video/videoSearch',
                method: 'POST',
                page: {
                    curr: 1
                },
                where: field,
                done: function () {
                    // 表单提交后，重新设置输入框的值
                    for (var key in field) {
                        $('[name="' + key + '"]').val(field[key]);
                    }
                    // const reloadEle = document.getElementById("reloadErrResource");
                    // const changeEle = document.getElementById("unEdit");

                    // 如果是未下载，则显示错误信息
                    if (parseInt(field.status) === videoStatus.UNDOWNLOADING.value) {
                        table.hideCol('Video', [{
                            field: 'createTime',
                            hide: true
                        }, {
                            field: 'medias',
                            hide: true
                        }, {
                            field: 'errMsg',
                            hide: false
                        },{
                            field: 'publishErr',
                            hide: true
                        }
                        ]);
                        // reloadEle.style.visibility = "visible";
                        // changeEle.style.visibility = "hidden";
                    } else {
                        table.hideCol('Video', [{
                            field: 'createTime',
                            hide: false
                        }, {
                            field: 'medias',
                            hide: false
                        }, {
                            field: 'errMsg',
                            hide: true
                        },{
                            field: 'publishErr',
                            hide: true
                        }
                        ]);
                        // if(selectStatus === videoStatus.PROCESSED.value){
                        //     changeEle.style.visibility = "visible";
                        // }else{
                        //     changeEle.style.visibility = "hidden";
                        // }
                        if(selectStatus === videoStatus.DEVICEUPLOAD.value){
                            table.hideCol('Video', [{
                                field: 'publishErr',
                                hide: false
                            }
                            ]);
                        }


                        // reloadEle.style.visibility = "hidden";
                    }

                    form.render('select');
                    layer.close(index); // 关闭 loading
                }
            });


            return false; // 阻止默认 form 跳转
        });

        /* **************** */
        /*     工具栏部分     */
        /* **************** */

        table.on('toolbar(Video)', function (obj) {
            var id = obj.config.id;
            var checkStatus = table.checkStatus(id);
            var data = checkStatus.data; // 获取选中的数据
            // var othis = lay(this);
            switch (obj.event) {
                case 'delete':
                    if (data.length === 0) return layer.msg('请至少选择一行');

                    layer.confirm('是否确认删除选中数据？', {
                        btn: ['确定', '关闭'] //按钮
                    }, function () {
                        var index = layer.load(0, {shade: false});
                        /* TODO: 执行批量删除选中 */
                        data.forEach(function (item) {
                            console.log("id:", item.id);
                            var id = {id: item.id};
                            $.ajax({
                                type: 'POST',
                                url: "/video/delete",
                                data: id,
                                dataType: 'Integer',
                                success: function (res) {
                                    console.log("rss : ", res);
                                }
                            })
                        });

                        setTimeout(function () {
                        }, 1000);

                        layer.close(index);
                        layer.msg("删除成功！",{icon:1})
                        table.reload('Video');
                        layer.load(0, {shade: false});
                        setTimeout(function () {
                            layer.closeAll(); // 关闭所有弹出层
                        },1000)

                    }, function () {

                    });

                    break;

                case 'reloadErrResource': {
                    if(selectStatus !== videoStatus.UNDOWNLOADING.value){
                        return layer.msg('仅对 未下载 状态视频有效！',{icon: 2,time: 1000});
                    }
                    if (data.length === 0) return layer.msg('请至少选择一行');

                    layer.confirm('是否重新下载选中的资源？', {
                        btn: ['确定', '关闭'] //按钮
                    }, function () {
                        var index = layer.load(0, {shade: false});

                        var idList = data.map(function (obj) {
                            return obj.userId;
                        });
                        idList = [...new Set(idList)];
                        console.log("list  : ", idList)
                        $.ajax({
                            type: 'POST',
                            url: "/admin/reloadErrByAccountIdArr",
                            data: JSON.stringify(idList),
                            contentType: "application/json",
                            dataType: 'json',
                            success: function (res) {

                            }
                        })

                        /* 遍历每行，每次执行一次 */
                        /* 5.7注释 修改为上传id数组 */
                        /*data.forEach(function(item) {
                            console.log("id:", item.id);
                            var id ={id:item.id};
                            $.ajax({
                                type: 'POST',
                                url: "/admin/reloadErrResource",
                                data: id,
                                dataType: 'Integer',
                                success: function (res) {

                                }
                            })
                        });*/
                        table.reload('Video');
                        layer.close(index);
                        layer.msg('请等待下载！', {
                            icon: 1,
                            time: 1000
                        });



                    }, function () {

                    });

                    break;
                }

                case 'unEdit':{
                    if(selectStatus !== videoStatus.PROCESSED.value){

                        return layer.msg("仅对 处理完成 状态的视频有效！", {icon: 2, time: 1000});
                    }

                    var checkStatus = table.checkStatus('Video');
                    var data = checkStatus.data;
                    var ids = data.map(function (item) {
                        return item.id;
                    });
                    if (ids.length === 0) {
                        return layer.msg('请选择待上传的视频！');
                    }

                    layer.confirm('是否不进行文案修改，直接进入处理视频？（确认后文案修改无效）', {
                        btn: ['确定', '关闭'] //按钮
                    }, function (){
                        var index = layer.load(0, {shade: false});
                        $.ajax({
                            type: 'POST',
                            url: "/admin/change/video/status",
                            contentType: "application/json", // 设置请求头为 JSON 格式
                            data: JSON.stringify(ids), // 将数据序列化为 JSON 字符串
                            dataType: "json", // 设置期望的返回数据类型
                            success: function (res) {
                                layer.close(index)
                                if(res.code === 0){
                                    layer.msg("修改成功！", {icon: 1})
                                }else{
                                    layer.msg("修改成功！", {icon: 2})
                                }
                                table.reload('Video')
                                layer.load(0, {shade: false});
                                setTimeout(function () {
                                    layer.closeAll(); // 关闭所有弹出层
                                },1000)

                            }
                        })
                    })
                    // if (data.length === 0) return layer.msg('请至少选择一行');

                    break;
                }



            }
            return false;
        });


        /* **************** */
        /*    渲染 table     */
        /* **************** */
        table.render({
            before: function (options) {
                // 设置下拉框数据
                const downLoadingSelect = document.getElementById('downLoadingSelect');
                // const changeEle = document.getElementById("unEdit");
                if (downLoadingSelect.options.length === 0) {
                    for (let item in videoStatus) {
                        let option = document.createElement('option');
                        option.value = videoStatus[item].value;
                        option.text = videoStatus[item].name;
                        downLoadingSelect.appendChild(option);
                    }
                }
                // changeEle.style.visibility = "hidden";

                // 使用 AJAX 请求获取选项数据
                $.ajax({
                    url: '/platform/platformAll',
                    type: 'POST',
                    dataType: 'json',
                    success: function (response) {

                        // 清空选择框
                        $('#platformSelect').empty();
                        // 添加默认选项
                        $('#platformSelect').append('<option value="">全部平台</option>');
                        // 根据返回的数据动态生成选项并添加到选择框中
                        $.each(response.data, function (index, item) {
                            $('#platformSelect').append('<option value="' + item.platformName + '">' + item.platformName + '</option>');
                        });

                    },
                    error: function (xhr, status, error) {
                        console.error('Failed to fetch options:', error);
                    }
                });
            },
            elem: '#Video',
            id: 'Video',
            url: '/video/videoSearch',
            where: {
                name: "",
                platformName: "",
                status: videoStatus.UNDOWNLOADING.value
            },
            // data:tempData,
            // group:5,
            method: 'post',
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            height: 'full-35', // 最大高度减去其他容器已占有的高度差
            css: [ // 重设当前表格样式
                '.layui-table-tool-temp{padding-right: 145px;}'
            ].join(''),
            cellMinWidth: 80,
            page: true,
            limit: 20,
            limits: [20, 50, 100, 200],
            // totalRow: true, // 开启合计行
            cols: [[
                {type: 'checkbox', fixed: 'left'},
                {
                    fixed: 'left', width: '50', title: '序号', sort: true, templet: function (d) {
                        return d.LAY_INDEX + 1;
                    }
                },
                {field: 'id', title: 'id', hide: true},
                {field: 'userName', width: '100', title: '源作者'},
                {field: 'title', width: '100', title: '标题'},
                {field: 'userId', width: '100', title: '源账户id', hide: true},
                {
                    field: 'status', width: '100', title: '状态', templet: function (d) {
                        for (let item in videoStatus) {
                            if (videoStatus[item].value === d.status) {
                                console.log("item = ", videoStatus[item])
                                if (d.status === videoStatus.UNDOWNLOADING.value) {
                                    return '<span style="color: #FF5722">' + videoStatus[item].name + '</span>'
                                } else {
                                    return '<span style="color: #16b777">' + videoStatus[item].name + '</span>'
                                }
                            }
                        }

                    }
                },
                {field: 'createTime', width: '200', title: '下载时间', sort: true, hide: true},
                {
                    field: 'medias', width: '120', minWidth: 100, title: '资源地址', hide: true, templet: function (d) {
                        var medias = JSON.parse(d.medias);
                        var html = '';
                        console.log("测试！看重载是否进入")
                        for (var i = 0; i < medias.length; i++) {
                            var media = medias[i];
                            if (media.media_type === 'video') {
                                if(selectStatus > videoStatus.UPLOADABLE.value){
                                    console.log("变为处理后视频！status = "+selectStatus)
                                    media.resource_url = media.resource_url.replace(/(\/)([^\/]+)$/, '/h-$2');
                                }
                                html += '<div>';
                                html += '<span style="color: #01aaed"></span> ';
                                if (media.resource_url != null) {
                                    html += '<a style="color: #01aaed" href="' + media.resource_url + '" target="_blank">视频 ' + (i + 1) + '</a> ';
                                }
                                if (media.preview_url != null) {
                                    html += '<a style="color: #01aaed" href="' + media.preview_url + '" target="_blank">&nbsp&nbsp封面 ' + (i + 1) + '</a>';
                                }
                                html += '</div>';
                            } else if (media.media_type === 'image') {
                                html += '<div>';
                                html += '<span style="color: #01aaed"></span> ';
                                if (media.resource_url != null) {
                                    html += '<a style="color: #01aaed" href="' + media.resource_url + '" target="_blank">图片 ' + (i + 1) + '</a> ';
                                }
                                if (media.preview_url != null) {
                                    html += '<a style="color: #01aaed" href="' + media.preview_url + '" target="_blank">&nbsp&nbsp封面 ' + (i + 1) + '</a>';
                                }
                                html += '</div>';
                            }
                        }
                        return html;
                    }
                },
                {
                    field:'publishErr', width: '200', title: '发布错误的平台',hide: true,
                },
                {field: 'errMsg', width: '500', title: '错误信息', hide: false},
                {fixed: 'right', title: '操作', width: 220, toolbar: '#barDemo', hide: false}

            ]],
            done: function () {

            },
            error: function (res, msg) {
                console.log(res, msg)
            }
        });


        /* ************************ */
        /*       单元格操作事件       */
        /* ************************ */
        // 触发单元格工具事件
        table.on('tool(Video)', function (obj) { // 双击 toolDouble
            var data = obj.data; // 获得当前行数据
            // console.log("单元格操作时间：tool(Video)-数据：",data);
            // 编辑文案
            if (obj.event === 'edit') {


                layer.open({
                    type: 1, // 页面层
                    title: '修改内容',
                    area: ['800px', '600px'], // 宽高
                    content: `
                        <style>
                            .custom-form-container {
                                padding: 20px;
                                background-color: #f2f2f2; /* 背景颜色 */
                                border-radius: 10px; /* 圆角 */
                            }
                            .custom-textarea {
                                width: 100%;
                                height: 450px;
                                border: 1px solid #ccc;
                                padding: 10px;
                                border-radius: 5px; /* 文本域的圆角 */
                                box-sizing: border-box;
                                resize: none; /* 禁止拖动改变大小 */
                            }
                            .layui-input-block {
                                margin-left: 0; /* 去掉左边距 */
                            }
                            .btn-container {
                                text-align: center;
                                margin-top: 20px;
                            }
                            .btn-container button {
                                margin: 0 10px;
                            }
                        </style>
                        <div class="custom-form-container">
                            <form class="layui-form" action="">
                                <div class="layui-form-item layui-form-text">
                                    <div class="layui-input-block">
                                        <textarea name="textareaField" placeholder="多行文本框" class="layui-textarea custom-textarea">` + data.title + `</textarea>
                                    </div>
                                </div>
                                <div class="btn-container">
                                    <button type="button" class="layui-btn" id="confirm-btn">确认</button>
                                    <button type="button" class="layui-btn layui-btn-primary" id="cancel-btn">取消</button>
                                </div>
                            </form>
                        </div>

                 `
                });
                if(selectStatus >= videoStatus.UPLOADABLE.value){
                    layer.msg('该文案已进行翻译，修改不会生效！')
                    return ;
                }else if(selectStatus === videoStatus.UNDOWNLOADING.value){
                    layer.msg('无文案，修改不会生效！')
                    return ;
                }

                document.getElementById('confirm-btn').addEventListener('click', function () {
                    // 获取输入框的内容
                    var textareaContent = document.querySelector('textarea[name="textareaField"]').value;
                    $.ajax({
                        url: "/video/modify/title",
                        type: "POST",
                        data: {
                            "id": data.id,
                            "title": textareaContent
                        },
                        success: function (res) {
                            // 在这里处理确认按钮的逻辑

                            console.log("修改成功", res);
                            layer.msg("修改成功！", {icon:1})
                            table.reload('Video');
                            layer.load(0, {shade: false});
                            setTimeout(function () {
                                layer.closeAll(); // 关闭所有弹出层
                            },1000)
                        },
                        error: function (res) {
                            console.log("修改失败", res);
                            layer.msg("修改失败！", {icon:1})
                            table.reload('Video');
                            layer.load(0, {shade: false});
                            setTimeout(function () {
                                layer.closeAll(); // 关闭所有弹出层
                            },1000)
                        }
                    })



                });


                // 重新渲染表单TODO：将修改的内容上传
                form.render();


            }
            else if(obj.event === 'report'){
                if(selectStatus < videoStatus.DEVICEDOWN.value){
                    layer.msg("该视频未上传，无错误报告", {icon: 5})
                }else{
                    $.ajax({
                        url: "/videoLog/get/List",
                        type: "POST",
                        data: {
                            "videoId": data.id,
                        },
                        success: function (res) {
                            console.log("获取成功", res);
                            // layer.msg("上报成功!");
                            layer.open({
                                type: 1, // 页面层
                                title: '错误报告',
                                area: ['800px', '600px'], // 宽高
                                content: `
                                    <div style="border: 1px solid #ddd; padding: 15px; background-color: #f9f9f9; border-radius: 8px; max-height: 500px; overflow-y: auto;">
                                        `+ res.data +`
                                    </div>
                                `
                                ,
                            })
                        },
                        error: function (res) {
                            console.log("获取失败", res);
                            layer.confirm("获取失败!",{btn:['关闭']});
                        }
                    })

                }

            }
            return false;
        });

        // 触发表格复选框选择
        table.on('checkbox(Video)', function (obj) {

        });


    });
</script>
</body>
</html>
